package com.alienlab.finder.web.rest;
import com.alienlab.finder.domain.AppUser;
import com.alienlab.finder.service.AppUserService;
import com.alienlab.finder.service.dto.UserInfoDTO;
import com.alienlab.finder.web.rest.errors.BadRequestAlertException;
import com.alienlab.finder.web.rest.util.ErrorResult;
import com.alienlab.finder.web.rest.util.HeaderUtil;
import com.alienlab.finder.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing AppUser.
 */
@RestController
@RequestMapping("/api")
public class AppUserResource {

    private final Logger log = LoggerFactory.getLogger(AppUserResource.class);

    private static final String ENTITY_NAME = "appUser";

    private final AppUserService appUserService;

    public AppUserResource(AppUserService appUserService) {
        this.appUserService = appUserService;
    }



    @ApiOperation(value="用户授权登录")
    @PostMapping("/app-users/userlogin")
    public ResponseEntity appUserLogin(@RequestParam String code) throws Exception {
        System.out.println("获取到的code");
        System.out.println(code);
        if ("".equals(code) || code==null) {
            throw new BadRequestAlertException("未获取用户code", ENTITY_NAME, "User's code  is not exists");
        }
        UserInfoDTO userInfoDTO =  appUserService.userLogin(code);
        if (userInfoDTO!=null){
            return  ResponseEntity.ok(userInfoDTO);
        }else{
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResult());
        }


    }

    @ApiOperation(value="存储sessionid")
    @PostMapping("/app-users/websocket")
    public ResponseEntity websocket(@RequestParam String open_id,@RequestParam String session_id) throws Exception {

        if ("".equals(open_id) || open_id==null) {
            throw new BadRequestAlertException("未获取用户open_id", ENTITY_NAME, "User's open_id  is not exists");
        }
        if ("".equals(session_id) || session_id==null) {
            throw new BadRequestAlertException("未获取用户session_id", ENTITY_NAME, "User's session_id  is not exists");
        }
        appUserService.creatOrupdateSessionid(open_id, session_id);
        return ResponseEntity.ok("{\"flag\":true}");


    }


    @ApiOperation(value="修改用户个人信息")
    @PutMapping("/app-users")
    public ResponseEntity updateAppUserinfo(@RequestParam String open_id,@RequestParam String name,@RequestParam Integer age,@RequestParam String phone,@RequestParam String we_chat,@RequestParam String address) throws Exception {
        log.debug("REST request to update AppUser : {}", open_id);
        if ("".equals(open_id) || open_id==null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "未获取到用户的open_id");
        }
        AppUser result = appUserService.updateAppuserInfo(open_id,name,age,phone,we_chat,address);

        if (result!=null){
            return  ResponseEntity.ok(result);
        }else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResult());
        }

    }

    @ApiOperation(value="修改用户个人微信昵称以及头像")
    @PutMapping("/app-users/wechatname")
    public ResponseEntity updateAppUserWehatname(@RequestParam String open_id,@RequestParam String wechatname,@RequestParam String headimage) throws Exception {
        log.debug("REST request to update AppUser : {}", open_id);
        if ("".equals(open_id) || open_id==null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "未获取到用户的open_id");
        }
        AppUser result = appUserService.updateWechatname(open_id,wechatname,headimage);

        if (result!=null){
            return  ResponseEntity.ok(result);
        }else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResult());
        }

    }


    @ApiOperation(value = "获取用户个人信息")
    @GetMapping("/app-users/getpersonalinfo")
    public ResponseEntity  getAppUser(@RequestParam String open_id) {
        log.debug("REST request to 获取用户个人信息 : {}", open_id);
        AppUser appUser = null;
        try {
            appUser = appUserService.getPersonnalInfo(open_id);
            return ResponseEntity.ok(appUser);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResult());
        }

    }


    /**
     * POST  /app-users : Create a new appUser.
     *
     * @param appUser the appUser to create
     * @return the ResponseEntity with status 201 (Created) and with body the new appUser, or with status 400 (Bad Request) if the appUser has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/app-users")
    public ResponseEntity<AppUser> createAppUser(@Valid @RequestBody AppUser appUser) throws URISyntaxException {
        log.debug("REST request to save AppUser : {}", appUser);
        if (appUser.getId() != null) {
            throw new BadRequestAlertException("A new appUser cannot already have an ID", ENTITY_NAME, "idexists");
        }
        AppUser result = appUserService.save(appUser);
        return ResponseEntity.created(new URI("/api/app-users/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * GET  /app-users : get all the appUsers.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of appUsers in body
     */
    @GetMapping("/app-users")
    public ResponseEntity<List<AppUser>> getAllAppUsers(Pageable pageable) {
        log.debug("REST request to get a page of AppUsers");
        Page<AppUser> page = appUserService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/app-users");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /app-users/:id : get the "id" appUser.
     *
     * @param id the id of the appUser to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the appUser, or with status 404 (Not Found)
     */
    @GetMapping("/app-users/{id}")
    public ResponseEntity<AppUser> getAppUser(@PathVariable Long id) {
        log.debug("REST request to get AppUser : {}", id);
        Optional<AppUser> appUser = appUserService.findOne(id);
        return ResponseUtil.wrapOrNotFound(appUser);
    }

    /**
     * DELETE  /app-users/:id : delete the "id" appUser.
     *
     * @param id the id of the appUser to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/app-users/{id}")
    public ResponseEntity<Void> deleteAppUser(@PathVariable Long id) {
        log.debug("REST request to delete AppUser : {}", id);
        appUserService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }



}
